//
//  PersonalViewController.m
//  SheShiDu
//
//  Created by 单剑秋 on 16/6/11.
//  Copyright © 2016年 单剑秋. All rights reserved.
//

#import "PersonalViewController.h"
#import "PersonalTableViewCell.h"
#import "UserCell.h"
#import "JQButton.h"
#import "QImageView.h"
#import "OpinionCell.h"
#import "ChartViewController.h"
#import "HouseViewController.h"
#import "DiaryViewController.h"
#import "AboutViewController.h"
#import "DiaryViewController.h"
#import <MessageUI/MessageUI.h>
#import "LoadingViewController.h"
#import "SetUpViewController.h"
#import "HomeViewController.h"

#define HEIGHT self.view.frame.size.height
#define WIDTH self.view.frame.size.width
@interface PersonalViewController ()<UITableViewDelegate, UITableViewDataSource, UIImagePickerControllerDelegate, UINavigationControllerDelegate, MFMailComposeViewControllerDelegate, PassDelegate, PassEndDelegate>

@property (nonatomic, strong)UITableView *personalTableView;

@property (nonatomic, strong)UIImagePickerController *imagePicker;
@property (nonatomic, strong)QImageView *selectedRightImage;

@end

@implementation PersonalViewController

- (void)viewWillAppear:(BOOL)animated
{
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    
//    void (^reBackL) (NSMutableDictionary *location) = ^(NSMutableDictionary *location) {
//        self.location = [NSMutableDictionary dictionaryWithDictionary:location];
////        _nameTF.text = [_location objectForKey:@"name"];
//        NSLog(@"%@~~~~", _location);
//    };
//    HomeViewController *HVC = [[HomeViewController alloc]init];
//    HVC.reBackL = reBackL;
    
}

- (void)viewDidDisappear:(BOOL)animated
{
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self createTableView];
    // 换头像
    [self changeHeader];
    
}

- (void)createTableView
{
    
    self.personalTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height - 49) style:UITableViewStylePlain];
    _personalTableView.delegate = self;
    _personalTableView.dataSource = self;
    
    [self.view addSubview:_personalTableView];
    [_personalTableView registerClass:[PersonalTableViewCell class] forCellReuseIdentifier:@"PersonalCell"];
    [_personalTableView registerClass:[UserCell class] forCellReuseIdentifier:@"UserCell"];
    [_personalTableView registerClass:[OpinionCell class] forCellReuseIdentifier:@"OpinionCell"];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 5;
    } else {
        return 3;
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            UserCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UserCell" forIndexPath:indexPath];
            // 取消cell点击
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.backgroundImgView.image = [UIImage imageNamed:@"effect"];
            [cell.messageButton setImage:[UIImage imageNamed:@"message"] forState:UIControlStateNormal];
            [cell.setUpButton setImage:[UIImage imageNamed:@"setUp"] forState:UIControlStateNormal];
            [cell.setUpButton addTarget:self action:@selector(setUpAction:) forControlEvents:UIControlEventTouchUpInside];
            if (_i == 0) {
                cell.telephoneLabel.text = @"主人未登录...";
                cell.telephoneLabel.textAlignment = 1;
            } else {
                cell.telephoneLabel.text = _userName;
            }
//            NSLog(@"%ld!!!", _i);
            cell.positionImgView.image = [UIImage imageNamed:@"position"];
            cell.positionLabel.text = self.location;
            [cell.orderButton setImage:[UIImage imageNamed:@"order"] forState:UIControlStateNormal];
            [cell.orderButton setTitle:@"我的订单" forState:UIControlStateNormal];
            [cell.livingButton setImage:[UIImage imageNamed:@"living"] forState:UIControlStateNormal];
            [cell.livingButton setTitle:@"直播间" forState:UIControlStateNormal];
            [cell.renovateButton setImage:[UIImage imageNamed:@"renovate"] forState:UIControlStateNormal];
            [cell.renovateButton setTitle:@"装修日志" forState:UIControlStateNormal];
            [cell.renovateButton addTarget:self action:@selector(diaryAction:) forControlEvents:UIControlEventTouchUpInside];
            return cell;
        } else {
            PersonalTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"PersonalCell" forIndexPath:indexPath];
            if (indexPath.row == 1) {
                cell.functionImgView.image = [UIImage imageNamed:@"home"];
                cell.functionLabel.text = @"房屋信息";
            } else if (indexPath.row == 2) {
                cell.functionImgView.image = [UIImage imageNamed:@"calculator"];
                cell.functionLabel.text = @"费用计算器";
            } else if (indexPath.row == 3) {
                cell.functionImgView.image = [UIImage imageNamed:@"loan"];
                cell.functionLabel.text = @"装修贷款";
            } else {
                cell.functionImgView.image = [UIImage imageNamed:@"financial"];
                cell.functionLabel.text = @"装修实拍图";
            }
            cell.symbolImgView.image = [UIImage imageNamed:@"right"];
            return cell;
        }
    } else {
        if (indexPath.row == 0) {
            OpinionCell *opCell = [tableView dequeueReusableCellWithIdentifier:@"OpinionCell" forIndexPath:indexPath];
            opCell.opinionImgView.image = [UIImage imageNamed:@"opinion"];
            opCell.functionLabel.text = @"意见投诉";
            opCell.symbolImgView.image = [UIImage imageNamed:@"right"];
            return opCell;
        } else if (indexPath.row == 1) {
            PersonalTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"PersonalCell" forIndexPath:indexPath];
            cell.functionImgView.image = [UIImage imageNamed:@"telephone"];
            cell.functionLabel.text = @"咨询电话";
            cell.telephoneLabel.text = @"0451-88888888";
            cell.symbolImgView.image = [UIImage imageNamed:@"right"];
            return cell;
        }
        else {
            PersonalTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"PersonalCell" forIndexPath:indexPath];
            cell.functionImgView.image = [UIImage imageNamed:@"about"];
            cell.functionLabel.text = @"关于设饰度";
            cell.symbolImgView.image = [UIImage imageNamed:@"right"];
            return cell;
        }
    }
}

- (void)setUpAction:(UIButton *)setUp
{
    SetUpViewController *SUVC = [[SetUpViewController alloc]init];
    SUVC.q = _i;
    SUVC.delegate = self;
    [self.navigationController pushViewController:SUVC animated:YES];
}

- (void)diaryAction:(UIButton *)diary
{
    DiaryViewController *DVC = [[DiaryViewController alloc] init];
    [self.navigationController pushViewController:DVC animated:YES];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    int Height = 0;
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            Height = HEIGHT * (606 / 1334.0);
        } else {
            Height = HEIGHT * (95 / 1334.0);
        }
    } else {
        Height = HEIGHT * (95 / 1334.0);
    }
    return Height;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return 0;
    } else {
        return 10;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *sectionView = [[UIView alloc] init];
    sectionView.backgroundColor = [UIColor colorWithRed:237 / 255.0 green:231 / 255.0 blue:227 / 255.0 alpha:1];
    return sectionView;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        if (indexPath.row == 1) {
            // 房屋信息
            HouseViewController *HVC = [[HouseViewController alloc] init];
            [self.navigationController pushViewController:HVC animated:YES];
        } else if (indexPath.row == 4) {
            // 装修实拍图
            ChartViewController *CVC = [[ChartViewController alloc] init];
            [self.navigationController pushViewController:CVC animated:YES];
        }
    } else if (indexPath.section == 1) {
        if (indexPath.row == 0) {
            // 意见反馈
            if(![MFMailComposeViewController canSendMail]) return;
            MFMailComposeViewController *vc = [[MFMailComposeViewController alloc] init];
            //设置邮件主题
            [vc setSubject:@"意见反馈"];
            //设置邮件内容
            [vc setMessageBody:@"意见" isHTML:NO];
            //设置收件人列表
            [vc setToRecipients:@[@"mao19900628@163.com"]];
            //设置抄送人列表
            [vc setCcRecipients:@[@"572472944@qq.com"]];
            //设置代理
            vc.mailComposeDelegate = self;
            //显示控制器
            [self presentViewController:vc animated:YES completion:nil];

            
        } else if (indexPath.row == 1) {
            // 打电话(客服)
            NSMutableString * str=[[NSMutableString alloc] initWithFormat:@"tel:%@",@"18545131225"];
            UIWebView * callWebview = [[UIWebView alloc] init];
            [callWebview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:str]]];
            [self.view addSubview:callWebview];
            
            //            NSString *allString = [NSString stringWithFormat:@"tel:18545131225"];
            //            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:allString]];
            
        }
        else if (indexPath.row == 2) {
            // 关于我们
            AboutViewController *aboutVC = [[AboutViewController alloc]init];
            [self.navigationController pushViewController:aboutVC animated:YES];
        }
    }
}

# pragma mark - 发邮件(意见反馈)
- (void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error
{
    [controller dismissViewControllerAnimated:YES completion:nil];
}

# pragma mark - 换头像
- (void)changeHeader
{
    self.imagePicker=[[UIImagePickerController alloc] init];
    _imagePicker.delegate = self;
    // 可编辑
    _imagePicker.allowsEditing = YES;
    self.selectedRightImage = [[QImageView  alloc] initWithFrame:CGRectMake(WIDTH * (281 / 750.0), HEIGHT * (606 / 1334.0) * (98 /606.0), HEIGHT *(184 / 606.0) * (606 / 1334.0), HEIGHT *(184 / 606.0) * (606 / 1334.0))];
    _selectedRightImage.image = [QImageView jq_captureCircleImage:[UIImage imageNamed:@"loadwait"]];
    [_personalTableView addSubview:_selectedRightImage];
    
    self.selectedRightImage.userInteractionEnabled = YES;
    
    UITapGestureRecognizer *tapPicture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(selectedImageForIcon)];
    [_selectedRightImage addGestureRecognizer:tapPicture];
}

# pragma mark - 头像轻拍手势
-(void)selectedImageForIcon
{
    
//    NSLog(@"%ld~~~", _i);
    if (_i == 0) {
        LoadingViewController *loadVC = [[LoadingViewController alloc]init];
        loadVC.delegate = self;
        void (^reBackMe) (NSMutableDictionary *dic) = ^(NSMutableDictionary *dic) {
            self.infoDic = [NSMutableDictionary dictionaryWithDictionary:dic];
            self.userName = [_infoDic objectForKey:@"name"];
        };
        loadVC.reBackMe = reBackMe;
        [self.navigationController presentViewController:loadVC animated:YES completion:^{
            
        }];
    } else {
        UIAlertController *alertController=[UIAlertController alertControllerWithTitle:@"" message:@"" preferredStyle:UIAlertControllerStyleActionSheet];
        UIAlertAction *actionCamera=[UIAlertAction actionWithTitle:@"打开相机" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            _imagePicker.sourceType=UIImagePickerControllerSourceTypeCamera;
            [self presentViewController:_imagePicker animated:YES completion:nil];
            
        }];
        
        UIAlertAction *actionPhotoLIbrary=[UIAlertAction actionWithTitle:@"打开相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            _imagePicker.sourceType=UIImagePickerControllerSourceTypePhotoLibrary;
            [self presentViewController:_imagePicker animated:YES completion:nil];
            
        }];
        
        UIAlertAction *actionPhotoAlbum=[UIAlertAction actionWithTitle:@"打开图库" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            _imagePicker.sourceType=UIImagePickerControllerSourceTypeSavedPhotosAlbum;
            [self presentViewController:_imagePicker animated:YES completion:nil];
            
        }];
        
        UIAlertAction *cancelAction=[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        
        [alertController addAction:actionCamera];
        
        [alertController addAction:actionPhotoAlbum];
        
        [alertController addAction:actionPhotoLIbrary];
        
        [alertController addAction:cancelAction];
        
        [self presentViewController:alertController animated:YES completion:nil];
        
    }
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(nullable NSDictionary<NSString *,id> *)editingInfo
{
    _selectedRightImage.image=[QImageView jq_captureCircleImage:image];
    [self dismissViewControllerAnimated:YES completion:nil];
    
}

- (void)passValue:(NSInteger)load
{
    _i = load;
    [_personalTableView reloadData];
//    NSLog(@"%ld+++", _i);
    // 头像判断
    if (_i == 0) {
        _selectedRightImage.image = [QImageView jq_captureCircleImage:[UIImage imageNamed:@"loadwait"]];
    } else {
        _selectedRightImage.image = [QImageView jq_captureCircleImage:[UIImage imageNamed:@"head"]];
    }
}

- (void)passEndValue:(NSInteger)deload :(NSInteger)deloads
{
    _p = deload;
    _q = deloads;
    _i = _q;
        NSLog(@"%ld+++", _p);
    // 头像判断
    if (_q == 0) {
        _selectedRightImage.image = [QImageView jq_captureCircleImage:[UIImage imageNamed:@"loadwait"]];
    } else if (_q == 1 && _p == 0) {
        _selectedRightImage.image = [QImageView jq_captureCircleImage:[UIImage imageNamed:@"head"]];
    } else if (_q == 1 && _p == 1) {
        _selectedRightImage.image = [QImageView jq_captureCircleImage:[UIImage imageNamed:@"loadwait"]];
    }
    [_personalTableView reloadData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
